#!/usr/bin/env ruby

$LOAD_PATH << File.expand_path("../../../lib/rubyFulguro/fulguro")

require 'fulguro'
include Fulguro

### PROCEDURES #########################################################


##################################################################
### MAIN #########################################################
##################################################################

imin = flgr2d_load_pgm('../../images/gray/beans.pgm')
imtmp = FLGR_Data2D.new(imin)
imFilter = FLGR_Data2D.new(imin)
imDistance = FLGR_Data2D.new(imin)
imMarker = FLGR_Data2D.new(imin)
imMaxima = FLGR_Data2D.new(imin)
imLabel = FLGR_Data2D.new(imin)
imWatershed = FLGR_Data2D.new(imin)

vmin = FLGR_Vector.new(imin.spp,imin.type)
vmax = FLGR_Vector.new(imin.spp,imin.type)

nhb1 = FLGR_Data2D.new(3,3,1,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb2 = FLGR_Data2D.new(5,5,1,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb3 = FLGR_Data2D.new(7,7,1,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb4 = FLGR_Data2D.new(9,9,1,imin.type,FLGR_RECT,FLGR_8_CONNEX)
nhb5 = FLGR_Data2D.new(11,11,1,imin.type,FLGR_RECT,FLGR_8_CONNEX)

flgr2d_replace(imin,imin,"==",255,254,imin)

## Filter
flgr2d_open(imtmp,imin,nhb1)
flgr2d_close(imFilter,imtmp,nhb1)

## Distance
flgr2d_replace(imtmp,imFilter,"<=",128,255,0)
flgr2d_distance(imDistance,imtmp,nhb1.connexity)

## Distance Maxima
flgr2d_regional_hmaxima(imMaxima,imDistance,1,nhb1.connexity)
flgr2d_replace(imtmp,imMaxima,'>',0,255,0)
flgr2d_dilate(imMaxima,imtmp,nhb4)

## Labelize Maxima
flgr2d_label(imLabel, imMaxima, nhb1.connexity)

## Watershed
flgr2d_watershed(imLabel, imin, nhb1.connexity)
flgr2d_watershed_build_line(imWatershed, imLabel, nhb1.connexity)
flgr2d_replace(imWatershed,imWatershed,"==",1,255,imin)


flgr2d_measure_min_max(imLabel,vmin,vmax)

print "Coffee Beans number : ",String(vmax[0]),"\n"



flgr2d_save_pgm(imFilter,"filter.pgm")
flgr2d_save_pgm(imDistance,"distance.pgm")
flgr2d_save_pgm(imMaxima,"maxima.pgm")
flgr2d_save_pgm(imLabel,"label.pgm")
flgr2d_save_pgm(imWatershed,"watershed.pgm")

